<?php

namespace addons\facrm\controller\facrm;

use app\admin\model\AuthGroup;
use addons\facrm\library\BackendApi;
use fast\Tree;
use think\Db;
use think\Exception;

/**
 * 业绩目标
 *
 */
class Achievement extends BackendApi
{

    /**
     * @var \app\admin\model\AuthGroup
     */
    protected $model = null;
    //当前登录管理员所有子组别
    protected $childrenGroupIds = [];
    protected $childrenAdminIds = [];
    //当前组别列表数据
    protected $groupdata = [];
    protected $groupList = [];
    //无需要权限判断的方法
    protected $noNeedRight = ['roletree'];

    public function _initialize()
    {
        parent::_initialize();
        $this->request->filter(['strip_tags']);
        $this->model = new AuthGroup();

        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);
        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $this->groupList = $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();

        Tree::instance()->init($groupList);
        $result = [];
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        } else {
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $result = array_merge($result, Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['pid'])));
            }
        }
        $groupName = [];
        foreach ($result as $k => $v) {
            $groupName[$v['id']] = $v['name'];
        }

        $this->groupdata = $groupName;
    }

    protected $temp_achievement = [
        'type' => 2,
        'type_id' => '',
        'year' => '',
        'january' => '',
        'february' => '',
        'march' => '',
        'april' => '',
        'may' => '',
        'june' => '',
        'july' => '',
        'august' => '',
        'september' => '',
        'october' => '',
        'november' => '',
        'december' => '',
        'yeartarget' => '',
    ];

    /**
     * 查看列表
     * @ApiMethod (get)
     */
    public function index()
    {
        $achievement = new \app\admin\model\facrm\Achievement();
        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter_w = [];
        if (isset($filter['search_time'])) {
            $filter_w['year'] = $filter['search_time'];
            unset($filter['search_time']);
        } else {
            $filter_w['year'] = date('Y', time());
        }
        if (isset($filter['config'])) {
            $filter_w['config'] = $filter['config'];
            unset($filter['config']);
        } else {
            $filter_w['config'] = 1;
        }
        $this->request->get(['filter' => json_encode($filter)]);


        if (isset($filter['group_id'])) {
            $list = AuthGroup::all($filter['group_id']);
        } else {
            $list = AuthGroup::all(array_keys($this->groupdata));
        }
        $list = collection($list)->toArray();
        $groupList = [];
        foreach ($list as $k => $v) {
            $groupList[$v['id']] = $v;
        }
        $list = [];
        foreach ($this->groupdata as $k => $v) {

            if (isset($groupList[$k])) {
                $groupList[$k]['name'] = $v;
                $groupList[$k]['achievement'] = $achievement->where('type', 2)->where($filter_w)->where('type_id', $k)->find();
                $groupList[$k]['achievement'] = $groupList[$k]['achievement'] ?: $this->temp_achievement;
                $list[] = $groupList[$k];

            }
        }
        $total = count($list);
        $result = array("total" => $total, "rows" => $list, "extend" => ['year' => $filter_w['year'], 'config' => isset($filter_w['config']) ? $filter_w['config'] : '']);

        $this->success('',$result);


    }


    /**
     * 员工业绩列表
     * @ApiMethod (get)
     */
    public function admin()
    {
        $achievement = new \app\admin\model\facrm\Achievement();
        //设置过滤方法
        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter_w = [];
        if (isset($filter['search_time'])) {
            $filter_w['year'] = $filter['search_time'];
            unset($filter['search_time']);
        } else {
            $filter_w['year'] = date('Y', time());
        }
        if (isset($filter['config'])) {
            $filter_w['config'] = $filter['config'];
            unset($filter['config']);
        } else {
            $filter_w['config'] = 1;
        }


        $this->model =new \app\admin\model\Admin();
        $childrenAdminIds = $this->getFilterChildrenAdminIds($filter);

        if ($childrenAdminIds) {
            $this->childrenAdminIds = $childrenAdminIds;
        }
        if (isset($filter['group_id'])) {
            unset($filter['group_id']);
        }

        $this->request->get(['filter' => json_encode($filter)]);
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->where('id', 'in', $this->childrenAdminIds)
            ->field(['password', 'salt', 'token'], true)
            ->order($sort, $order)
            ->paginate($limit);
        $this->temp_achievement['type'] = 3;
        foreach ($list as $k => &$row) {
            $row['achievement'] = $achievement->where('type', 3)->where($filter_w)->where('type_id', $row['id'])->find();
            $row['achievement'] = $row['achievement'] ?: $this->temp_achievement;

        }
        unset($v);
        $result = array("total" => $list->total(), "rows" => $list->items(), "extend" => ['year' => $filter_w['year'], 'config' => isset($filter_w['config']) ? $filter_w['config'] : '']);
        $this->success('',$result);
    }

    /**
     * 团队业绩编辑(单条)
     * @ApiMethod (POST)
     */
    public function edit()
    {
        $param = $this->request->param('row/a');
        $field = $param['field'];
        if (!isset($param['config']) || !in_array($param['config'], [1, 2])) {
            $this->error(__("业绩方式有误"));
        }
        if (!isset($param['year']) && $param['year'] < 2000) {
            $this->error(__("年份有误"));
        }
        if (!isset($param['group_id']) && $param['group_id'] < 0) {
            $this->error(__("权限组有误"));
        }
        $where = [
            'type' => 2,
            'type_id' => $param['group_id'],
            'year' => $param['year'],
            'config' => $param['config'],
        ];
        $achievement = new \app\admin\model\facrm\Achievement();
        $row = $achievement->where($where)->find();

        if (!is_numeric($param[$field]) || $param[$field] < 0) {
            $this->error(__("请输入数字"));
        }
        if (!$row) {
            //添加一条新记录
            $this->temp_achievement['type_id'] = $param['group_id'];
            $this->temp_achievement['year'] = $param['year'];
            $this->temp_achievement['config'] = $param['config'];
            $row = $achievement->create($this->temp_achievement);

            if (!$row) {
                $this->error(__("插入数据失败"));
            }
            $row = $achievement->find($row->id);
        }

        try {

            $old_val = $row->$field;
            if ($old_val == $param[$field]) {
                $this->error(__("没有修改"));
            } elseif ($old_val > $param[$field]) {
                $row->yeartarget = $row->yeartarget - ($old_val - $param[$field]);
            } elseif ($old_val < $param[$field]) {
                $row->yeartarget = $row->yeartarget + ($param[$field] - $old_val);
            }
            $row->$field = $param[$field];
            $row->config = $param['config'];
            $row->save();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success();
    }

    /**
     * 成员业绩编辑(单条)
     * @param null $ids
     * @ApiMethod (POST)
     */
    public function aedit()
    {
        $param = $this->request->param('row/a');
        $field = $param['field'];
        if (!isset($param['year']) && $param['year'] < 2000) {
            $this->error(__("年份有误"));
        }
        if (!isset($param['admin_id']) && $param['admin_id'] < 0) {
            $this->error(__("权限组有误"));
        }
        if (!isset($param['config']) || !in_array($param['config'], [1, 2])) {
            $this->error(__("业绩方式有误"));
        }
        $where = [
            'type' => 3,
            'type_id' => $param['admin_id'],
            'year' => $param['year'],
            'config' => $param['config'],
        ];
        $achievement = new \app\admin\model\facrm\Achievement();
        $row = $achievement->where($where)->find();
        if (!is_numeric($param[$field]) || $param[$field] < 0) {
            $this->error(__("请输入数字"));
        }
        if (!$row) {
            //添加一条新记录
            $this->temp_achievement['type_id'] = $param['admin_id'];
            $this->temp_achievement['year'] = $param['year'];
            $this->temp_achievement['type'] = 3;
            $this->temp_achievement['config'] = $param['config'];
            $row = $achievement->create($this->temp_achievement);

            if (!$row) {
                $this->error(__("插入数据失败"));
            }
            $row = $achievement->find($row->id);
        }

        try {

            $old_val = $row->$field;
            if ($old_val == $param[$field]) {
                $this->error(__("没有修改"));
            } elseif ($old_val > $param[$field]) {
                $row->yeartarget = $row->yeartarget - ($old_val - $param[$field]);
            } elseif ($old_val < $param[$field]) {
                $row->yeartarget = $row->yeartarget + ($param[$field] - $old_val);
            }
            $row->$field = $param[$field];
            $row->save();

        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success();
    }

    /**
     * 团队批量设置
     */
    public function batchTeam(){
        if ($this->request->isPost()) {
            $param = $this->request->param('row/a');
            if (!isset($param['config']) || !in_array($param['config'], [1, 2])) {
                $this->error(__("业绩方式有误"));
            }
            if (!isset($param['year']) && $param['year'] < 2000) {
                $this->error(__("年份有误"));
            }
            if (!isset($param['group_id']) && $param['group_id'] < 0) {
                $this->error(__("部门有误"));
            }
            $where = [
                'type' => 2,
                'year' => $param['year'],
                'config' => $param['config'],
            ];

            $result=false;

            if ($param['group_id']==0){
                //全部
                unset($param['group_id']);
                foreach ($this->groupList as $g){
                    $achievement = new \app\admin\model\facrm\Achievement();
                    $where['type_id']=$g['id'];
                    $row = $achievement->where($where)->find();
                    $this->temp_achievement=array_merge($this->temp_achievement,$param);
                    $this->temp_achievement['type_id'] = $where['type_id'];
                    $this->temp_achievement['year'] = $where['year'];
                    if (!$row) {
                        //添加一条新记录
                        $result=$achievement->create($this->temp_achievement);
                    }else{
                        $result=$row->save($this->temp_achievement);
                    }
                }

                $this->success();

            }else{
                $achievement = new \app\admin\model\facrm\Achievement();
                //某一个部门
                $where['type_id']=$param['group_id'];
                unset($param['group_id']);

                $row = $achievement->where($where)->find();
                $this->temp_achievement=array_merge($this->temp_achievement,$param);
                $this->temp_achievement['type_id'] = $where['type_id'];
                $this->temp_achievement['year'] = $where['year'];
                if (!$row) {
                    //添加一条新记录
                    $result=$achievement->create($this->temp_achievement);
                }else{
                    $result=$row->save($this->temp_achievement);
                }
            }
            if ($result){
                $this->success();
            }else{
                $this->error(__("添加失败"));
            }


        }
        $this->error(__("提交方式错误"));
    }

    /**
     * 成员批量设置
     */
    public function batchAdmin(){
        if ($this->request->isPost()) {
            $param = $this->request->param('row/a');
            if (!isset($param['config']) || !in_array($param['config'], [1, 2])) {
                $this->error(__("业绩方式有误"));
            }
            if (!isset($param['year']) && $param['year'] < 2000) {
                $this->error(__("年份有误"));
            }
            if (!isset($param['admin_id'])) {
                $this->error(__("员工有误"));
            }
            $where = [
                'type' => 3,
                'year' => $param['year'],
                'config' => $param['config'],
            ];

            $result=false;
            if ($param['admin_id']){
                $this->childrenAdminIds=explode(",",$param['admin_id']);
            }
            //全部
            unset($param['admin_id']);
            $lists = \app\admin\model\Admin::where('id', 'in', $this->childrenAdminIds)
                ->field(['password', 'salt', 'token'], true)
                ->select();


            foreach ($lists as $g){
                $achievement = new \app\admin\model\facrm\Achievement();
                $where['type_id']=$g['id'];
                $row = $achievement->where($where)->find();
                $this->temp_achievement=array_merge($this->temp_achievement,$param);
                $this->temp_achievement['type_id'] = $where['type_id'];
                $this->temp_achievement['year'] = $where['year'];
                $this->temp_achievement['type']=$where['type'];
                if (!$row) {
                    //添加一条新记录
                    $result=$achievement->create($this->temp_achievement);
                }else{
                    $result=$row->isUpdate(true)->save($this->temp_achievement);
                }
            }

            $this->success();
        }

        $this->error(__("提交方式错误"));
    }



    /**
     * 过滤查找子用户
     * @param $filter
     * @return array|void
     */
    protected function getFilterChildrenAdminIds($filter)
    {
        $childrenAdminIds = [];
        if (isset($filter['group_id'])) {
            $childrenAdminIds = [];
            if ($filter['group_id'] > 0) {
                Tree::instance()->init($this->groupList);
                $groupIds = Tree::instance()->getChildrenIds($filter['group_id'], true);

                $authGroupList = \app\admin\model\AuthGroupAccess::
                field('uid,group_id')
                    ->where('group_id', 'in', $groupIds)
                    ->select();
                foreach ($authGroupList as $k => $v) {
                    if (in_array($v['uid'], $childrenAdminIds)) continue;
                    $childrenAdminIds[] = $v['uid'];
                }
                if (!$childrenAdminIds) {

                    return $this->error("该组下面没有成员");
                }
            }
        }
        return $childrenAdminIds;
    }
}
